package znbkTestPaperRdtz.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;

import com.example.lancooznbk.R;

import znbkChangeCollection.ChangeCollectionEntityModel;
import znbkChangeCollection.ChangeCollectionPresenter.ChangeCollectionPresenter;
import znbkListRdtz.entity.HeatPointExtensionListEntity;
import com.example.lancooznbk.view.base.BaseActivity;
import com.example.lancooznbk.view.base.BaseFragment;
import com.example.lancooznbk.view.base.ILoadPaperView;
import com.example.lancooznbk.view.widget.EmptyMainLayout;
import com.example.lancooznbk.view.widget.LoadingDialog;
import com.example.lancooznbk.view.widget.ScaleButton;
import com.lancoo.dictionary.activity.DictionaryActicity;
import com.lancoo.reviewsystem.utils.ToastUtils;
import com.lancoo.rxretrofitlibrary.Api.UserInfo;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import java.util.Locale;

import lancooControl.AndroidBug5497Workaround;
import lancooControl.Control;
import lancooControl.PopupWindowMoreFunction;
import znbkListSc.ZnbkPaperScInfor;
import znbkTestPaperInfor.ZnbkPaperDef;
import znbkTestPaperInfor.ZnbkPaperInfor;
import znbkTestPaperRdtz.fragmentAdapter.HeatPointExtensionPaperFragmentAdapter;
import znbkTestPaperRdtz.ZnbkPaperRdtzInfor;
import znbkTestPaperRdtz.presenter.HeatPointExtensionPaperPresenter;
import znbkTestPaperRdtz.entity.HeatPointExtensionPaperEntity;
import znbkTestPaperRdtz.saveRdtzPaper.SaveHeatPointExtensionPaperPresenter;

/**
 * Created by Administrator on 2018\3\14 0014.
 */

public class HeatPointExtensionPaperActivity extends BaseActivity implements View.OnLayoutChangeListener,ILoadPaperView<HeatPointExtensionPaperEntity> {

    private ScaleButton mSBtnBack;//返回按钮
    private TextView mTvTittle;
    private ScaleButton mSBtnMore;

    public static ViewPager mVp;
    private HeatPointExtensionPaperFragmentAdapter mAdapter;
    HeatPointExtensionPaperPresenter mPresenter;
    public static HeatPointExtensionPaperEntity mEntityRdtz;


    //Activity最外层的Layout视图
    private View activityRootView;
    //屏幕高度
    private int screenHeight = 0;
    //软件盘弹起后所占高度阀值
    private int keyHeight = 0;

    private HeatPointExtensionListEntity.ResourceBean mEntity;
    public static final  String PAPER_ENTITY = "paperEntity";
    public static final String PAPER_FROM = "paperFrom";

    public int mQuesOrPaperFrom;
    private LoadingDialog mLoadingDialog;


    public  static void launch(BaseFragment mContext, HeatPointExtensionListEntity.ResourceBean entity, @ZnbkPaperDef.PaperFrom int quesOrPaperFrom){
        ZnbkPaperRdtzInfor.CreatTime = entity.getUpdateTime();
        ZnbkPaperRdtzInfor.RecommendNumberOfTimes = entity.getHotIndex();
        ZnbkPaperRdtzInfor.ResID = entity.getItemID();
        ZnbkPaperRdtzInfor.HotType = entity.getHotType();
        ZnbkPaperRdtzInfor.ResType = entity.getResType();
        ZnbkPaperRdtzInfor.Title = entity.getTitle();

        if(entity.getResType().equals("Q")) {
            ZnbkPaperRdtzInfor.Flag = 0;
        }else{
            ZnbkPaperRdtzInfor.Flag = 1;
        }
        ZnbkPaperInfor.ItemFrom = 4;
        Bundle bundle = new Bundle();
        bundle.putSerializable(PAPER_ENTITY,entity);
        bundle.putInt(PAPER_FROM,quesOrPaperFrom);
        Intent intent = new Intent(mContext.getContext(), HeatPointExtensionPaperActivity.class);
        intent.putExtras(bundle);
        mContext.startActivityForResult(intent,1);
    }

    @Override
    public int attachLayoutRes() {
        return R.layout.znbk_activity_paper_easy;
    }

    @Override
    protected void initViews() {
        AndroidBug5497Workaround.assistActivity(this);
        mPresenter = new HeatPointExtensionPaperPresenter(this);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null){
            mEntity = (HeatPointExtensionListEntity.ResourceBean) bundle.getSerializable(PAPER_ENTITY);
            mQuesOrPaperFrom = bundle.getInt(PAPER_FROM);
        }

        //核心代码.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

        initView();

        activityRootView = findViewById(R.id.main);
        //获取屏幕高度
        screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();
        //阀值设置为屏幕高度的1/3
        keyHeight = screenHeight/3;

    }

    @Override
    protected void updateViews(boolean isRefresh) {
        mSBtnMore.setVisibility(View.GONE);
        ZnbkPaperRdtzInfor.IsFromSpl = false;
        mPresenter.getData(isRefresh);
    }


    private String getStringTime(int cnt) {
        int hour = cnt/3600;
        int min = cnt % 3600 / 60;
        int second = cnt % 60;
        if(hour>0){
            return String.format(Locale.CHINA,"%02d:%02d:%02d",hour,min,second);
        }else{
            return String.format(Locale.CHINA,"%02d:%02d",min,second);
        }
    }



    /*
    * 初始化界面控件
    * */
    private void initView(){

        mEmptyViewLayout = (EmptyMainLayout) findViewById(R.id.layout_loading);

        /*
        * 返回按钮菜单相关设置
        * */
        mSBtnBack = (ScaleButton) findViewById(R.id.sbtn_back);
        mSBtnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                savePaperRdtz();
            }
        });


        /*
        * 页面头部-》收藏详情：mTvTittle
        * */
        mTvTittle = (TextView) findViewById(R.id.tv_title);
        mTvTittle.setText(R.string.znbk_titleHeatPointExtension);

        /*
        * 更多功能按钮菜单相关信息
        * */
        mSBtnMore = (ScaleButton) findViewById(R.id.sbtn_more);
        mSBtnMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mEntityRdtz!=null) {
                    initPopupWindowMoreFunction();
                }else {
                    Toast.makeText(getApplicationContext(),"数据加载中，请稍后重试...",Toast.LENGTH_SHORT).show();
                }
            }
        });

        mVp = (ViewPager) findViewById(R.id.viewpager);

    }

    /*********************
     * ******************
     *实现试卷明细解析
     * *****************
     ******************/
    /************************************************************************************************************************/

    @Override
    public void loadPaperData(HeatPointExtensionPaperEntity data) {

        mEntityRdtz = data;

//        ZnbkPaperInfor.QuesBrief = data.getTKQue().getQuesBrief();
//        ZnbkPaperInfor.TypeName = data.getTKQue().getTypeName();
        //这里因为是3.0一下版本，所以需继承FragmentActivity，通过getSupportFragmentManager()获取FragmentManager
        //3.0及其以上版本，只需继承Activity，通过getFragmentManager获取事物
        FragmentManager fm = getSupportFragmentManager();
        //初始化自定义适配器MyFragmentPageAdapter
        mAdapter =  new HeatPointExtensionPaperFragmentAdapter(fm);
        MyOnPageChangeListener myOnPageChangeListener = new MyOnPageChangeListener();
        mVp.setOnPageChangeListener(myOnPageChangeListener);
        //绑定自定义适配器
//        if(data.getAnswerState() == 2){
//            mAdapter.paperHasSubmit();
//        }
        mVp.setAdapter(mAdapter);

        if(data!=null){
            mSBtnMore.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void loadComplete(boolean hasComplete) {

    }

    @Override
    public void openExamReportDialog() {

//        feedBackDialogRight();

    }

    @Override
    public void openAssessDialog() {

    }

    @Override
    public void updatingResult(boolean isSucceed) {
        mLoadingDialog.dismiss();
        if (isSucceed){
        }else {
            ToastUtils.showShort("提交失败");
        }
    }

    @Override
    public void updatingReportResult(boolean isReportSucceed) {

    }

    public  LoadingDialog getLoadingDialog(){
        return mLoadingDialog;
    }

    @Override
    public RxAppCompatActivity getHolderActivity() {
        return null;
    }



    /************************************************************************************************************************/
    /*
    * LazyViewPage切换事件监听
    * */
    class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {
//			Log.e("onPageScrolled==111==: ", "==arg0=="+arg0);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
//			Log.e("onPageScrolled==111==: ", "==arg0=="+arg0);
        }

        @Override
        public void onPageSelected(int arg0) {

        }

    }


    //隐藏虚拟键盘:Fragment进行切换的时候使用
    public  void HideKeyboard() {
        /**隐藏软键盘**/
        View viewK = this.getWindow().peekDecorView();
        if(viewK != null){
            InputMethodManager inputmanger = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(viewK.getWindowToken(), 0);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /*
    * 监听系统home事件
    * */
    @Override
    protected void onUserLeaveHint() {
        super.onUserLeaveHint();
    }

    /*
    * 监听系统返回事件
    * */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            savePaperRdtz();
            return false;
        }
        return false;
    }



    /******************************************更多功能popupwindow****************************************************/

    private PopupWindowMoreFunction mPopupWindowMoreFunction;
    private void initPopupWindowMoreFunction(){
        if (mPopupWindowMoreFunction == null) {
            //自定义的单击事件
            OnClickLintener paramOnClickListener = new OnClickLintener();
            mPopupWindowMoreFunction = new PopupWindowMoreFunction(this, paramOnClickListener, Control.dip2px(this,140), Control.dip2px(this,80));
            //监听窗口的焦点事件，点击窗口外面则取消显示
            mPopupWindowMoreFunction.getContentView().setOnFocusChangeListener(new View.OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (!hasFocus) {
                        mPopupWindowMoreFunction.dismiss();
                    }
                }
            });
        }


        //显示当前试题的收藏情况
        if(!mEntityRdtz.isIsFavourite()) {
            PopupWindowMoreFunction.ImvDifficultQuestion.setBackgroundResource(R.mipmap.image_collect_unfocus);
            PopupWindowMoreFunction.TvDifficultQuestion.setText("加入收藏");
            PopupWindowMoreFunction.TvDifficultQuestion.setTextColor(getResources().getColor(R.color.white));
        }else if(mEntityRdtz.isIsFavourite()){
            PopupWindowMoreFunction.ImvDifficultQuestion.setBackgroundResource(R.mipmap.image_collect_focus);
            PopupWindowMoreFunction.TvDifficultQuestion.setText("取消收藏");
            PopupWindowMoreFunction.TvDifficultQuestion.setTextColor(getResources().getColor(R.color.yellow));
        }

//设置默认获取焦点
        mPopupWindowMoreFunction.setFocusable(true);
//以某个控件的x和y的偏移量位置开始显示窗口
        mPopupWindowMoreFunction.showAsDropDown(mSBtnMore, Control.dip2px(this,-120), Control.dip2px(this,15));
//如果窗口存在，则更新
        mPopupWindowMoreFunction.update();
    }
    class OnClickLintener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.layout_dictionary:
                    System.out.println("=======电子词典=========");
                    mPopupWindowMoreFunction.dismiss();
                    startActivity(new Intent(getApplicationContext(), DictionaryActicity.class));
                    break;
                case R.id.layout_difficult_question:
                    System.out.println("=======收藏与否=========");
                    int CollectionFlag = -1;
                    if(!mEntityRdtz.isIsFavourite()) {
                        CollectionFlag = 1;
                        mEntityRdtz.setIsFavourite(true);
                        PopupWindowMoreFunction.ImvDifficultQuestion.setBackgroundResource(R.mipmap.image_collect_focus);
                        PopupWindowMoreFunction.TvDifficultQuestion.setText("取消收藏");
                        PopupWindowMoreFunction.TvDifficultQuestion.setTextColor(getResources().getColor(R.color.yellow));
                    }else if(mEntityRdtz.isIsFavourite()){
                        CollectionFlag = 0;
                        mEntityRdtz.setIsFavourite(false);
                        PopupWindowMoreFunction.ImvDifficultQuestion.setBackgroundResource(R.mipmap.image_collect_unfocus);
                        PopupWindowMoreFunction.TvDifficultQuestion.setText("加入收藏");
                        PopupWindowMoreFunction.TvDifficultQuestion.setTextColor(getResources().getColor(R.color.white));
                    }
                    String QuesID = mEntityRdtz.getResID();

                    String Theme = "";
                    if(!mEntityRdtz.getResFromTK().getQuesBrief().equals("")){
                        Theme = mEntityRdtz.getResFromTK().getQuesBrief();
                    }else{
                        if(mEntityRdtz.getResFromTK().getChildList().size()>0) {
                            if (!mEntityRdtz.getResFromTK().getChildList().get(0).getChildAsk().equals("")) {
                                Theme = mEntityRdtz.getResFromTK().getChildList().get(0).getChildAsk();
                            } else {
                                Theme = mEntityRdtz.getResFromTK().getChildList().get(0).getSubChildList().get(0).getSubChildAsk();
                            }
                        }
                    }
                    String GenreID =  mEntityRdtz.getResFromTK().getGenreID();
                    String TypeNo =  mEntityRdtz.getResFromTK().getTypeNo();
                    String ResType =  mEntityRdtz.getResFromTK().getResType();
                    if(ResType.equals("Q")){
                        ResType =  TypeNo;
                    }

                    ZnbkPaperScInfor.changeCollectionEntityModel =  new ChangeCollectionEntityModel(CollectionFlag,
                            GenreID,QuesID,ResType, UserInfo.StageNo, UserInfo.StuId,UserInfo.SubjectId,Theme,TypeNo);

                    changeCollection();
                    break;

                default:
                    break;
            }

        }

    }


    /*
    * 加入收藏、取消收藏
    * */
    ChangeCollectionPresenter mChangeCollectionPresenter;
    private void changeCollection(){
        mChangeCollectionPresenter = new ChangeCollectionPresenter(this,mQuesOrPaperFrom);
        mChangeCollectionPresenter.getData(false);
    }
    /*************************************************************************************************************/

    @Override
    protected void onResume() {
        super.onResume();
        //添加layout大小发生改变监听器
        activityRootView.addOnLayoutChangeListener(this);
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {

        if (bottom > oldBottom){
            //输入法软键盘关闭
            Log.d(">>>>>>>>>crg", "输入法软键盘关闭: ");
        } else if (bottom < oldBottom){
            //输入法软键盘打开
            Log.d(">>>>>>>>>crg", "输入法软键盘打开: ");
        }

    }

    /*
* 保存单道试题作答信息
* */
    SaveHeatPointExtensionPaperPresenter mSaveHeatPointExtensionPaperPresenter;
    private void savePaperRdtz(){
        mSaveHeatPointExtensionPaperPresenter = new SaveHeatPointExtensionPaperPresenter(this,mQuesOrPaperFrom);
        mSaveHeatPointExtensionPaperPresenter.getData(false);
    }

}